'use strict';

const Controller = require('egg').Controller;
const { SuccessModel, FailModel } = require('../resModel/index')
const jwt = require('jsonwebtoken')

// 1. 校验
// 2. 参数
// 3. 查询数据库
// 4. 返回数据模型
class HomeController extends Controller {

  async register() {
    const errors = this.app.validator.validate({
      phone: 'string',
      password: 'string'
     }, this.ctx.request.body)
    console.log('errors:', errors)
    if (!errors) {
      const { phone, password } = this.ctx.request.body;
      const response = await this.app.mysql.get('users', { phone })
      if (!response) {
        const insertData = await this.app.mysql.insert('users', {
          password: this.ctx.helper.getPassword(password),
          phone
        })
        if (insertData.insertId) {
          this.ctx.body = new SuccessModel({inserid: insertData.insertId}, '注册成功')
        } else {
          this.ctx.body = new FailModel('注册fail')
        }
      } else {
        this.ctx.body = new FailModel('用户已经存在')
      }
    } else {
      this.ctx.body = new FailModel(errors, '参数校验失败')
    }
  }

  async login() {
    const errors = this.app.validator.validate({
      phone: 'string',
      password: 'string'
     }, this.ctx.request.body)

    if (!errors) {
      const { phone, password } = this.ctx.request.body;
      const response = await this.app.mysql.get('users', {
          phone,
          password: this.ctx.helper.getPassword(password),
        })
      if (response) {
        const { phone, id, createTime } = response;
        const token = jwt.sign({phone, id, createTime}, this.app.config.keys, {
          expiresIn: '24h'
        })
        this.ctx.body = new SuccessModel({token}, '登陆成功')
      } else {
        this.ctx.body = new FailModel(response, '登陆失败')
      }
    } else {
      this.ctx.body = new FailModel(errors, '参数校验失败')
    }
  }



  async index() {
    const { ctx } = this;
    const errors = this.app.validator.validate({ id: 'id' }, this.ctx.query)
    ctx.body = {
      code: 0,
      errors
    }
  }

  async find() {
    const { ctx } = this;
    const errors = this.app.validator.validate({ id: 'id' }, this.ctx.request.body)
    ctx.body = {
      code: 0,
      errors
    }
  }

}

module.exports = HomeController;
